package com.ww.juc.jd.async.basic.diy;

import java.util.concurrent.TimeUnit;

public class Bootstrap {

    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        Worker worker = bootstrap.newWorker();

        Wrapper wrapper = new Wrapper();
        wrapper.setWorker(worker);
        wrapper.setParam("hi");

        bootstrap.doWorker(wrapper).addListener(obj -> {
            System.out.println("当前线程：" + Thread.currentThread().getName());
            System.out.println("执行结果：" + obj);
        });
    }

    private Wrapper doWorker(Wrapper wrapper) {
        new Thread(() -> {
            Worker worker = wrapper.getWorker();
            String result = worker.action(wrapper.getParam());
            wrapper.getListener().result(result);
        }).start();

        return wrapper;
    }

    private Worker newWorker() {
        return obj -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            return obj + " callback!";
        };
    }
}
